<?php

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Constants\RedisKey;
use App\Constants\ServerList;
use App\Context\UserInfoContext;
use App\Controller\InsideService\GameListInside;
use App\Middleware\AdminMiddleware;
use App\Model\QmGameList;
use App\Model\QmGamePlatform;
use App\Service\ToolService;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\Redis\Redis;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Context;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

#[Controller(prefix: '/admin/GameList'), Middleware(AdminMiddleware::class)]
class GameListController extends BaseController {
    /**
     * 获取游戏列表
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'index')]
    public function index(): array {
        $userDataArr = $this->uInfo();
        $limit = $this->request->query('size', config('apiadmin.admin_list_default'));
        $name = $this->request->query('name', '');
        $status = $this->request->query('status', '');

        $obj = QmGameList::query()->where('status', '>', 0);
        if ($userDataArr['user_data']['bind_games']) {
            $bindGames = explode(',', $userDataArr['user_data']['bind_games']);
            $obj = $obj->whereIn('hash', $bindGames);
        } else {
            $obj = $obj->where('hash', '');
        }
        if (strlen($status)) {
            $obj = $obj->where('status', $status);
        }
        if ($name) {
            $obj = $obj->where('name', 'like', "%{$name}%");
        }
        $listObj = $obj->orderByDesc('id')->paginate((int)$limit);

        return $this->buildSuccess([
            'list'  => $listObj->items(),
            'count' => $listObj->total()
        ]);
    }

    #[GetMapping(path: 'getList')]
    public function getList(): array {
        $keywords = $this->request->query('keyword', '');

        return $this->buildSuccess($this->getListData($keywords, true));
    }

    /**
     * 获取全部游戏
     * @return array
     */
    #[GetMapping(path: 'getAllGames')]
    public function getAllGames(): array {
        return $this->buildSuccess($this->getListData());
    }

    /**
     * 获取可用的游戏列表
     * @param string $keywords
     * @param bool $needFilter
     * @return array
     */
    #[GetMapping(path: 'getListData')]
    public function getListData(string $keywords = '', bool $needFilter = false): array {
        $userDataArr = $this->uInfo();
        $platformList = QmGamePlatform::query()->get();
        $platformList = ToolService::buildArrFromObj($platformList, 'id');

        $res = [];
        $games = QmGameList::query();
        if ($keywords) {
            $games = $games->where('name', 'like', "%{$keywords}%");
        }
        if ($needFilter) {
            $game_hash = ServerList::ADMIN_BIND_GAMES[$userDataArr['server_code']];
            $games = $games->whereIn('hash', $game_hash);
        }
        $games = $games->where('status', '>', 0)->get();

        $gameName = [];
        foreach ($games as $game) {
            $gameName[] = $game['name'];
            if (!empty($platformList[$game['platform']])) {
                $game['name'] .= ' - ' . $platformList[$game['platform']]['title'];
            }
            $res[] = [
                'value' => $game['hash'],
                'label' => $game['name']
            ];
        }

        return [
            'list'         => $res,
            'platformList' => $platformList,
            'games'        => array_unique($gameName)
        ];
    }

    /**
     * 新增游戏
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[PostMapping(path: 'add')]
    public function add(): array {
        $userDataObj = Context::get(UserInfoContext::class);
        $type = $this->request->post('type');

        $obj = new QmGameList();
        $obj->name = $this->request->post('name');
        $obj->hash = md5(uniqid(mt_rand(), true));
        $obj->type = array_pop($type);
        $obj->app_id = $this->request->post('app_id');
        $obj->app_name = $this->request->post('app_name');
        $obj->app_secret = $this->request->post('app_secret');
        $obj->platform = $this->request->post('platform');
        $obj->status = $this->request->post('status');
        $obj->save();

        $bindGames = $userDataObj->userInfo['user_data']['bind_games'];
        if ($bindGames) {
            $bindGamesArr = explode(',', $bindGames);
        }
        $bindGamesArr[] = $obj->hash;
        $userDataObj->updateUserInfo(['bind_games' => implode(',', $bindGamesArr)], true);

        return $this->buildSuccess();
    }

    /**
     * 游戏状态编辑
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[GetMapping(path: 'changeStatus')]
    public function changeStatus(): array {
        $id = $this->request->query('id');
        $status = $this->request->query('status');

        $res = QmGameList::query()->find($id);
        $res->status = $status;
        $res->save();

        return $this->buildSuccess();
    }

    /**
     * 编辑游戏
     * @return array
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    #[PostMapping(path: 'edit')]
    public function edit(): array {
        $userDataObj = Context::get(UserInfoContext::class);
        $type = $this->request->post('type');

        $obj = QmGameList::query()->find($this->request->post('id'));
        $obj->name = $this->request->post('name');
        $obj->type = array_pop($type);
        $obj->app_id = $this->request->post('app_id');
        $obj->app_name = $this->request->post('app_name');
        $obj->app_secret = $this->request->post('app_secret');
        $obj->platform = $this->request->post('platform');
        $obj->status = $this->request->post('status');
        $obj->save();

        $bindGames = $userDataObj->userInfo['user_data']['bind_games'];
        if ($bindGames) {
            $bindGamesArr = explode(',', $bindGames);
        }
        $bindGamesArr[] = $obj->hash;
        $userDataObj->updateUserInfo(['bind_games' => implode(',', $bindGamesArr)], true);

        return $this->buildSuccess();
    }

    /**
     * 删除游戏【逻辑删除】
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    #[GetMapping(path: 'del')]
    public function del(): array {
        $id = $this->request->query('id');
        $old = QmGameList::query()->find($id);

        if ($old) {
            $redis = ApplicationContext::getContainer()->get(Redis::class);
            $redis->del(RedisKey::GM_INFO . ':' . $id);
            $redis->del(RedisKey::GM_INFO . ':' . $old->getAttribute('hash'));

            $old->status = 0;
            $old->save();
        } else {
            return $this->buildFailed(ErrorCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }
}